package ex.com.jm.food.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;



import com.opensymphony.xwork2.ActionSupport;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class FileUploadAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	//static String uploadPath=ServletActionContext.getServletContext().getRealPath("upload");
	//上传文件存放路径   
   /// private final static String UPLOADDIR = uploadPath.replaceAll("\\\\","/");
    private final static String UPLOADDIR = "D:/javaee/workspace/e9ding/WebContent/upload";  
    //上传文件集合 / 
    private List<File> file;   
    //上传文件名集合   
    private List<String> fileFileName;   
    //上传文件内容类型集合   
    private List<String> fileContentType; 
	private String fileN;	
	private String fileName;
	private File f; 
	private String url;
	@SuppressWarnings("unused")
	private String filePath;
    public List<File> getFile() {   
        return file;   
    }   

    public void setFile(List<File> file) {   
        this.file = file;   
    }   

   public List<String> getFileFileName() {   
       return fileFileName;   
   }   

    public void setFileFileName(List<String> fileFileName) {   
        this.fileFileName = fileFileName;   
    }   

    public List<String> getFileContentType() {   
        return fileContentType;   
    }   

    public void setFileContentType(List<String> fileContentType) {   
        this.fileContentType = fileContentType;   
    }   

    public String getFileN() {
		return fileN;
	}

	public void setFileN(String fileN) {
		this.fileN = fileN;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public File getF() {
		return f;
	}

	public void setF(File f) {
		this.f = f;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	
	public String toFileupLoad(){
		return "fileupload";
	}

	public String fileupload() throws Exception {   
        System.out.println(this.getFileFileName());  
        String string="";
        for (int i = 0; i < file.size(); i++) {   
            //循环上传每个文件   
        	string=uploadFile(i);   
        } 
        System.out.println("fileName=====>>"+fileName);
        return "image";
       /* Map<String, String> map=new HashMap<String, String>();
        JSONArray fileArray = null;
        if(string=="success"){
              map.put("filePath", url);
              fileArray=JSONArray.fromObject(map);
            }
         HttpServletResponse response = ServletActionContext.getResponse();  
		 response.setContentType("text/javascript"); 
		 PrintWriter out=null;
			try {
				out = response.getWriter();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			out.print(fileArray);
           //out.write(url);
*/    }   

    //执行上传功能   
    private String  uploadFile(int i) throws FileNotFoundException, IOException {   
        try {   
            InputStream in = new FileInputStream(file.get(i));   
            //String dir = ServletActionContext.getRequest().getRealPath(UPLOADDIR);  
            String dir=UPLOADDIR;
            System.out.println(dir);
            String filePath=dir;
            File fileLocation = new File(dir);  
            //此处也可以在应用根目录手动建立目标上传目录  
            if(!fileLocation.exists()){  
                boolean isCreated  = fileLocation.mkdir();  
                if(!isCreated) {  
                    //目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。  
                }  
            }  
            fileName=this.getFileFileName().get(i); 
            String name = fileName.substring(fileName.lastIndexOf(".")); // 得到后缀名
            f=file.get(i);
            File file2=new File(fileName);
            if (name.equals(".jpg") || name.equals(".gif")||name.equals(".png")) { 
            	 // InputStream input = new FileInputStream(getUpload()); // 输入流
	                System.out.println(in);
	                BufferedImage bi = ImageIO.read(in); // 得到BufferedImage对象
	                System.out.println(bi);
	                if (bi != null) { // 如果图片正确则不为空，不正确时为空
	                    int width = bi.getWidth(); // 上传图片的宽
	                    int height = bi.getHeight(); // 上传图片的高
	                    System.out.println("宽：" + width + "\t高：" + height);
	                    if (this.htmlUpload(file2, filePath)) {
	                        System.out.println("上传成功！");
	                        //this.uploadJPGfile(bi, name, filePath);
	                      //将上传的文件路径存入数据库	                  
	            			url=filePath+"/"+fileName;
	            			System.err.println(url);
	            		  //如何获得系统日期
	            		    Date d = new Date();
	            		  //String str = d.toString();
	            		  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd  kk:mm:ss ");//其中yyyy-MM-dd是你要表示的格式
	            		  //可以任意组合，不限个数和次序；具体表示为：MM-month,dd-day,yyyy-year;kk-hour,mm-minute,ss-second;
	            		  //把其转化为 String
	            		  String str=sdf.format(d);
	            		  System.out.println("The date is : "+str);	    
	            			if(url!=null){
	            				System.out.println("success");
	            				return "success";				
	            			}else {
	            				System.out.println("error");
	            				return "error";
	            			}
	                    } else {
	                        System.out.println("上传失败！");
	                    }
	                } else {
	                    System.out.println("你选择的图片错误或者该图片已经损坏！"); // 给出提示
	                }
	            } else {
	                // 当文件不是图片文件时，在此进行代码编写
	                if (this.htmlUpload(file2, filePath)) {
	                    System.out.println("上传成功！");
	                } else {
	                    System.out.println("上传失败！");
	                }
	            }
	        } catch (Exception e) {

	        }
	        return null;
	    }
    
    /**
     * Html控件得到的File文件上传方法
     * 
     * @param file
     *            File对象
     * @param filePath
     *            上传文件存放位置
     * @return
     */
    private boolean htmlUpload(File file, String filePath) {
        try {
        	System.out.println(f);
            InputStream input = new FileInputStream(f); // 输入流
            String name = file.getName(); // 原文件路劲名
            System.out.println("input:"+input);
            System.out.println("name:"+name);
            
            int random = (int) (Math.random() * 10000); // 随机数
            fileName = System.currentTimeMillis() + random
                    + name.substring(name.indexOf(".")); // 通过得到系统时间加随机数生成新文件名，避免重复
           System.out.println(System.currentTimeMillis());
           System.out.println(random);
           System.out.println(name.substring(name.indexOf(".")));
            System.out.println("filename1:"+fileName);
            byte[] buff = new byte[4096]; // 缓冲区
            FileOutputStream output = new FileOutputStream(filePath +"/"+ fileName); // 输出流
            System.out.println("output:"+output);
            int bytecount = 1;
            while ((bytecount = input.read(buff, 0, 4096)) != -1) { // 当input.read()方法，不能读取到字节流的时候，返回-1
                output.write(buff, 0, bytecount); // 写入字节到文件
            }
            output.flush();
            output.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    public boolean uploadJPGfile(BufferedImage img, String name,
            String filePath) {
        try {
            // 转为jpg标准格式//
            int random = (int) (Math.random() * 10000); // 随机数
            fileN = System.currentTimeMillis() + random + name; // 通过得到系统时间加随机数生成新文件名，避免重复
            System.out.println("filename2:"+fileN);
            if (img != null) {
                int new_w = 150;
                int new_h = 100;
                BufferedImage tag = new BufferedImage(new_w, new_h,BufferedImage.TYPE_INT_RGB);
                tag.getGraphics().drawImage(img, 0, 0, new_w, new_h, null); // 绘制缩小后的图
                FileOutputStream out = new FileOutputStream(filePath +"/"+ fileN);
                System.err.println("=======>>>>>"+filePath +"/"+ fileN);
                System.out.println("out:"+out);
                System.out.println("filepaths:"+filePath);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                System.out.println("encoder:"+encoder);
                encoder.encode(tag);
                System.out.println("tag:"+tag);
                out.close();
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            System.out.println("异常错误！");
            return false;
        }
	
    }
    
    
    public void showImage() throws IOException {
    	String imgurl=UPLOADDIR+"/"+fileName;
    	
		File file = new File(fileName);
		System.out.println("=======>>>>"+fileName);
		if (file.exists()) {
			// 如果用户选择了文件，则一定存在。
			FileInputStream fis = new FileInputStream(file);
			int size = fis.available(); // 得到文件大小
			byte data[] = new byte[size];
			fis.read(data); // 读数据
			fis.close();
			 HttpServletResponse response = ServletActionContext.getResponse();  
			response.setContentType("image/gif"); // 设置返回的文件类型
			response.setContentLength((int) file.length());
			OutputStream os = response.getOutputStream();
			os.write(data);
			os.flush();
			os.close();
		}
    	
	}
}
